<template>
  <div class="verification-login">
    <!-- App风格弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>提示</h3>
        </div>
        <div class="modal-body">
          {{ modalMessage }}
        </div>
        <div class="modal-footer">
          <button class="modal-btn confirm" @click="closeModal">确定</button>
        </div>
      </div>
    </div>
    
    <!-- 验证码横幅 -->
    <div v-if="showDevCode" class="dev-code-banner">
      【健康医疗】您的验证码：{{ devCodeMsg.split(':')[1]?.trim() }}，请勿泄露。
    </div>
    
    <!-- 状态栏 -->
    <div class="status-bar">
      <span class="time">12:00</span>
      <div class="status-icons">
        <span class="signal"></span>
        <span class="wifi"></span>
        <span class="battery"></span>
      </div>
    </div>

    <!-- 头部 -->
    <div class="header">
      <div class="close-btn" @click="goBack">×</div>
      <div class="register-link" @click="goToRegister1">注册</div>
    </div>
    
    <!-- 主要内容 -->
    <div class="content">
      <!-- 标题 -->
      <div class="title-section">
        <h1 class="main-title">手机验证码登录</h1>
        <p class="subtitle">未注册手机号将自动注册并登录</p>
      </div>
      
      <!-- 登录表单 -->
      <div class="login-form">
        <!-- 手机号输入 -->
        <div class="input-group">
          <div class="input-icon">
            <div class="phone-icon"></div>
          </div>
          <div class="input-wrapper">
            <span class="country-code">+86</span>
            <input 
              type="text" 
              v-model="phoneNumber" 
              placeholder="请输入11位手机号"
              class="phone-input"
              maxlength="11"
            >
          </div>
        </div>
        
        <!-- 验证码输入 -->
        <div class="input-group">
          <div class="input-icon">
            <div class="lock-icon"></div>
          </div>
          <div class="input-wrapper">
            <input 
              type="text" 
              v-model="verificationCode" 
              placeholder="请输入验证码"
              class="code-input"
              maxlength="6"
            >
            <button 
              class="get-code-btn" 
              @click="getVerificationCode"
              :disabled="!canGetCode || countdown > 0"
            >
              {{ countdown > 0 ? `${countdown}s` : '获取' }}
            </button>
          </div>
        </div>
        
        <!-- 收不到验证码链接 -->
        <div class="help-link">
          <a href="#" @click="handleCannotReceiveCode">收不到验证码</a>
        </div>
      </div>
      
      <!-- 登录按钮 -->
      <div class="login-actions">
        <button 
          class="login-btn" 
          @click="handleLogin"
          :disabled="!canLogin"
        >
          登录
        </button>
        
        <div class="alternative-login">
          <a href="#" @click="goToPasswordLogin">用账号密码登录</a>
        </div>
      </div>
      
      <!-- 快速登录 -->
      <div class="quick-login">
        <div class="divider">
          <span class="divider-text">快速登录</span>
        </div>
        <div class="login-methods">
          <div class="method wechat" @click="handleWechatLogin">
            <div class="wechat-icon"></div>
          </div>
          <div class="method apple" @click="handleAppleLogin">
            <div class="apple-icon"></div>
          </div>
        </div>
      </div>
      
      <!-- 协议同意 -->
      <div class="agreement">
        <label class="checkbox-container">
          <input type="checkbox" v-model="agreed" class="checkbox">
          <span class="checkmark"></span>
        </label>
        <span class="agreement-text">
          我已阅读并同意
          <a href="#" class="link">《中国移动认证服务条款》</a>
          和
          <a href="#" class="link">AI智能医疗辅助系统 用户协议、隐私政策以及儿童个人信息保护政策</a>
        </span>
      </div>
    </div>

    <!-- 底部手势条 -->
    <div class="gesture-bar"></div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

export default defineComponent({
  name: 'VerificationLogin',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const phoneNumber = ref('')
    const verificationCode = ref('')
    const agreed = ref(false)
    const countdown = ref(0)
    const loading = ref(false)
    const isPhoneRegistered = ref(false)
    

    
    // 检查手机号注册状态
    const checkPhoneRegistrationStatus = async (phone: string) => {
      if (phone.length === 11 && /^1[3-9]\d{9}$/.test(phone)) {
        try {
          const response = await axios.get(`http://localhost:3000/users/phone-list`)
          if (response.data.success) {
            const phoneList = response.data.data
            isPhoneRegistered.value = phoneList.some((item: any) => item.phoneNumber === phone)
          } else {
            isPhoneRegistered.value = false
          }
        } catch (error) {
          console.error('检查手机号注册状态失败:', error)
          isPhoneRegistered.value = false
        }
      } else {
        isPhoneRegistered.value = false
      }
    }

    // 页面加载时检查URL参数
    onMounted(() => {
      if (route.query.phone) {
        phoneNumber.value = route.query.phone as string
        // 检查注册状态
        checkPhoneRegistrationStatus(phoneNumber.value)
      }
    })

    // 监听手机号变化
    watch(phoneNumber, (newPhone) => {
      checkPhoneRegistrationStatus(newPhone)
    })
    
    // 弹窗相关
    const showModal = ref(false)
    const modalMessage = ref('')
    
    // 验证码横幅相关
    const devCodeMsg = ref('')
    const showDevCode = ref(false)
    let devCodeTimer: any = null

    // 计算属性
    const canGetCode = computed(() => {
      return phoneNumber.value.length === 11 && 
             /^1[3-9]\d{9}$/.test(phoneNumber.value) && 
             isPhoneRegistered.value
    })

    const canLogin = computed(() => {
      return phoneNumber.value.length === 11 && 
             verificationCode.value.length === 6 && 
             agreed.value
    })

    // 显示弹窗
    const showAppModal = (message: string) => {
      modalMessage.value = message
      showModal.value = true
    }

    // 关闭弹窗
    const closeModal = () => {
      showModal.value = false
    }



    // 获取验证码
    const getVerificationCode = async () => {
      if (!canGetCode.value) {
        if (!isPhoneRegistered.value) {
          showAppModal('该手机号未注册，请先进行注册')
        } else {
          showAppModal('请输入正确的手机号')
        }
        return
      }

      try {
        loading.value = true
        const response = await axios.post('http://localhost:3000/users/send-code', {
          phoneNumber: phoneNumber.value
        })
        
        if (response.data.success) {
          // 展示开发环境验证码横幅
          devCodeMsg.value = `健康医疗验证码: ${response.data.code}`
          showDevCode.value = true
          if (devCodeTimer) clearTimeout(devCodeTimer)
          devCodeTimer = setTimeout(() => {
            showDevCode.value = false
          }, 4000)
          
          // 开始倒计时
          countdown.value = 60
          const timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        } else {
          showAppModal(response.data.message)
        }
      } catch (error: any) {
        showAppModal(error.response?.data?.message || '发送验证码失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    // 登录处理
    const handleLogin = async () => {
      if (!canLogin.value) {
        showAppModal('请填写完整信息并同意协议')
        return
      }

      try {
        loading.value = true
        const response = await axios.post('http://localhost:3000/users/login', {
          phoneNumber: phoneNumber.value,
          verificationCode: verificationCode.value
        })
        
        if (response.data.success) {
          // 存储登录token和用户信息
          localStorage.setItem('token', response.data.token)
          localStorage.setItem('userInfo', JSON.stringify(response.data.user))
          
          // 显示成功消息
          showAppModal(response.data.message)
          
          // 跳转到首页
          setTimeout(() => {
            router.push('/home')
          }, 1200)
        } else {
          showAppModal(response.data.message)
        }
      } catch (error: any) {
        // 如果是未注册错误，显示特殊弹窗
        if (error.response?.data?.message?.includes('未注册')) {
          showUnregisteredModal()
        } else {
          showAppModal(error.response?.data?.message || '登录失败，请稍后重试')
        }
      } finally {
        loading.value = false
      }
    }

    // 显示未注册弹窗
    const showUnregisteredModal = () => {
      modalMessage.value = '该手机号未注册，请先进行注册'
      showModal.value = true
    }

    // 其他功能
    const goBack = () => {
      router.back()
    }

    const handleCannotReceiveCode = () => {
      showAppModal('请联系客服处理')
    }

    const goToPasswordLogin = () => {
      router.push('/password-login')
    }

    const handleWechatLogin = () => {
      showAppModal('微信登录功能开发中...')
    }

    const handleAppleLogin = () => {
      showAppModal('Apple登录功能开发中...')
    }

    async function goToRegister1() {
      // 检查手机号是否已输入
      if (!phoneNumber.value || phoneNumber.value.length !== 11) {
        showAppModal('请先输入正确的手机号')
        return
      }
      
      // 跳转到注册页面，并传递手机号
      router.push({
        path: '/register',
        query: { phone: phoneNumber.value }
      })
    }

    async function registerPhoneNumber() {
      try {
        // 发送验证码
        const codeResponse = await axios.post('http://localhost:3000/users/send-code', {
          phoneNumber: phoneNumber.value
        })
        
        if (codeResponse.data.success) {
          // 展示开发环境验证码横幅
          devCodeMsg.value = `健康医疗验证码: ${codeResponse.data.code}`
          showDevCode.value = true
          if (devCodeTimer) clearTimeout(devCodeTimer)
          devCodeTimer = setTimeout(() => {
            showDevCode.value = false
          }, 4000)
          
          // 提示用户输入验证码
          showAppModal('验证码已发送，请输入验证码完成注册')
          
          // 清空验证码输入框，让用户重新输入
          verificationCode.value = ''
          
          // 开始倒计时
          countdown.value = 60
          const timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        } else {
          showAppModal(codeResponse.data.message)
        }
      } catch (error: any) {
        showAppModal(error.response?.data?.message || '发送验证码失败，请稍后重试')
      }
    }



    return {
      phoneNumber,
      verificationCode,
      agreed,
      countdown,
      loading,
      canGetCode,
      canLogin,
      getVerificationCode,
      handleLogin,
      goBack,
      handleCannotReceiveCode,
      goToPasswordLogin,
      handleWechatLogin,
      handleAppleLogin,
      // 弹窗相关
      showModal,
      modalMessage,
      showAppModal,
      closeModal,
      goToRegister1,
      // 验证码横幅相关
      devCodeMsg,
      showDevCode
    }
  }
})
</script>

<style scoped>
.verification-login {
  min-height: 100vh;
  background: #ffffff;
  position: relative;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* App风格弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  animation: fadeIn 0.2s ease-out;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 280px;
  max-width: 90vw;
  overflow: hidden;
  animation: slideUp 0.3s ease-out;
}

.modal-header {
  padding: 20px 20px 0 20px;
  text-align: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.modal-body {
  padding: 20px;
  text-align: center;
  color: #666;
  font-size: 16px;
  line-height: 1.4;
}

.modal-footer {
  padding: 0 20px 20px 20px;
  display: flex;
  justify-content: center;
}

.modal-btn {
  padding: 12px 32px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.modal-btn.confirm {
  background: #007AFF;
  color: white;
}

.modal-btn.confirm:hover {
  background: #0056CC;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    opacity: 0; 
    transform: translateY(20px) scale(0.95);
  }
  to { 
    opacity: 1; 
    transform: translateY(0) scale(1);
  }
}

/* 验证码横幅 */
.dev-code-banner {
  position: fixed;
  left: 50%;
  bottom: 80px;
  transform: translateX(-50%);
  min-width: 220px;
  max-width: 80vw;
  background: #fff;
  color: #222;
  text-align: center;
  padding: 14px 24px;
  border-radius: 18px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.18), 0 1.5px 4px rgba(0,0,0,0.10);
  font-size: 16px;
  letter-spacing: 1px;
  z-index: 9999;
  border: 1px solid #e5e5e5;
  animation: sms-pop 0.3s;
}

@keyframes sms-pop {
  0% { opacity: 0; transform: translateX(-50%) translateY(30px) scale(0.95);}
  100% { opacity: 1; transform: translateX(-50%) translateY(0) scale(1);}
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 44px;
  background: #ffffff;
}

.time {
  font-size: 14px;
  font-weight: 600;
  color: #000;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 4px;
}

.signal, .wifi, .battery {
  width: 20px;
  height: 12px;
  background: #000;
  border-radius: 2px;
}

/* 头部 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  margin-bottom: 40px;
}

.close-btn {
  font-size: 24px;
  color: #333;
  cursor: pointer;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.register-link {
  color: #007AFF;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
}

/* 主要内容 */
.content {
  padding: 0 20px;
}

/* 标题部分 */
.title-section {
  text-align: center;
  margin-bottom: 40px;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #000;
  margin: 0 0 8px 0;
}

.subtitle {
  font-size: 14px;
  color: #8E8E93;
}

/* 登录表单 */
.login-form {
  margin-bottom: 30px;
}

.input-group {
  display: flex;
  align-items: center;
  background: #F2F2F7;
  border-radius: 12px;
  padding: 12px 16px;
  margin-bottom: 16px;
}

.input-icon {
  margin-right: 12px;
}

.phone-icon {
  width: 20px;
  height: 20px;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%238E8E93"><path d="M17,19H7V5H17M17,1H7C5.89,1 5,1.89 5,3V21A2,2 0 0,0 7,23H17A2,2 0 0,0 19,21V3C19,1.89 18.1,1 17,1Z"/></svg>') no-repeat center;
  background-size: contain;
}

.lock-icon {
  width: 20px;
  height: 20px;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%238E8E93"><path d="M12,17A2,2 0 0,0 14,15C14,13.89 13.1,13 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V10C4,8.89 4.9,8 6,8H7V6A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,3A3,3 0 0,0 9,6V8H15V6A3,3 0 0,0 12,3Z"/></svg>') no-repeat center;
  background-size: contain;
}

.input-wrapper {
  display: flex;
  align-items: center;
  flex: 1;
  position: relative;
}

.country-code {
  color: #007AFF;
  font-weight: 500;
  margin-right: 8px;
}

.phone-input,
.code-input {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 16px;
  color: #000;
  outline: none;
}

.phone-input::placeholder,
.code-input::placeholder {
  color: #8E8E93;
}

.get-code-btn {
  background: #007AFF;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
}

.get-code-btn:disabled {
  background: #C7C7CC;
  cursor: not-allowed;
}

.help-link {
  text-align: right;
  margin-top: 0;
  margin-bottom: 16px;
}

.help-link a {
  color: #007AFF;
  text-decoration: none;
  font-size: 14px;
}

/* 登录操作 */
.login-actions {
  margin-bottom: 40px;
}

.login-btn {
  width: 100%;
  height: 50px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  margin-bottom: 16px;
  transition: background-color 0.2s;
}

.login-btn:hover:not(:disabled) {
  background: #0056CC;
}

.login-btn:disabled {
  background: #C7C7CC;
  cursor: not-allowed;
}

.alternative-login {
  text-align: center;
}

.alternative-login a {
  color: #007AFF;
  text-decoration: none;
  font-size: 14px;
}

/* 快速登录 */
.quick-login {
  margin-bottom: 40px;
}

.divider {
  position: relative;
  text-align: center;
  margin-bottom: 30px;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #E5E5EA;
}

.divider-text {
  background: #ffffff;
  padding: 0 16px;
  color: #8E8E93;
  font-size: 14px;
  position: relative;
  z-index: 1;
}

.login-methods {
  display: flex;
  justify-content: center;
  gap: 40px;
}

.method {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.method:hover {
  transform: scale(1.1);
}

.wechat {
  background: #07C160;
}

.apple {
  background: #000;
}

.wechat-icon {
  width: 24px;
  height: 24px;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M8.5,13.5A1.5,1.5 0 0,1 7,12A1.5,1.5 0 0,1 8.5,10.5A1.5,1.5 0 0,1 10,12A1.5,1.5 0 0,1 8.5,13.5M15.5,13.5A1.5,1.5 0 0,1 14,12A1.5,1.5 0 0,1 15.5,10.5A1.5,1.5 0 0,1 17,12A1.5,1.5 0 0,1 15.5,13.5M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z"/></svg>') no-repeat center;
  background-size: contain;
}

.apple-icon {
  width: 24px;
  height: 24px;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white"><path d="M18.71,19.5C17.88,20.74 17,21.95 15.66,21.97C14.32,22 13.89,21.18 12.37,21.18C10.84,21.18 10.37,21.95 9.1,22C7.79,22.05 6.8,20.68 5.96,19.47C4.25,17 2.94,12.45 4.7,9.39C5.57,7.87 7.13,6.91 8.82,6.88C10.1,6.86 11.32,7.75 12.11,7.75C12.89,7.75 14.37,6.68 15.92,6.84C16.57,6.87 18.39,7.1 19.56,8.82C19.47,8.88 17.39,10.1 17.41,12.63C17.44,15.65 20.06,16.66 20.09,16.67C20.06,16.74 19.67,18.11 18.71,19.5M13,3.5C13.73,2.67 14.94,2.04 15.94,2C16.07,3.17 15.6,4.35 14.9,5.19C14.21,6.04 13.07,6.7 11.95,6.61C11.8,5.46 12.36,4.26 13,3.5Z"/></svg>') no-repeat center;
  background-size: contain;
}

/* 协议同意 */
.agreement {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 40px;
  padding: 0 10px;
}

.checkbox-container {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  flex-shrink: 0;
  margin-top: 2px;
}

.checkbox {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 20px;
  width: 20px;
  background-color: #fff;
  border: 2px solid #C7C7CC;
  border-radius: 4px;
  transition: all 0.2s;
}

.checkbox:checked ~ .checkmark {
  background-color: #007AFF;
  border-color: #007AFF;
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

.checkbox:checked ~ .checkmark:after {
  display: block;
}

.checkbox-container .checkmark:after {
  left: 6px;
  top: 2px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.agreement-text {
  font-size: 12px;
  color: #8E8E93;
  line-height: 1.4;
}

.link {
  color: #007AFF;
  text-decoration: none;
}

.link:hover {
  text-decoration: underline;
}

/* 底部手势条 */
.gesture-bar {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 134px;
  height: 5px;
  background: #000;
  border-radius: 3px;
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 375px) {
  .main-title {
    font-size: 20px;
  }
  
  .login-methods {
    gap: 30px;
  }
  
  .method {
    width: 45px;
    height: 45px;
  }
}


</style> 